/*
	jumper : Copyright 2011 Dale J Williams

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/
package lads.jumper.pixmap {
	
	import flash.display.BitmapData;
	import flash.geom.Point;
	import lads.flad.scene.collision.ICollidable;
	import lads.flad.scene.SceneObject;
	
	public class PixMap extends SceneObject implements ICollidable {
		
		private var _bitmapData:BitmapData;
		private var tiles:Vector.<PixTile>;
		private var _startP:Point;
		private var _endP:Point;
		
		public function PixMap(bitmapData:BitmapData = null) {
			super("pixMap");
			tiles = new Vector.<PixTile>();
			_startP = new Point();
			_endP = new Point();
			this.bitmapData = bitmapData;
		}
		
		private function update():void {
			if (!_bitmapData || _bitmapData.width < 1 || _bitmapData.height < 1) return;
			var numTiles:int = _bitmapData.width * _bitmapData.height;
			var tile:PixTile;
			
			while (tiles.length < numTiles) tiles.push(PixTile(addChild(new PixTile())));
			while (tiles.length > numTiles) removeChild(tiles.pop());
			
			var color:uint;
			var by:int = _bitmapData.height;
			var bx:int;			
			while (by-- > 0) {
				bx = _bitmapData.width;
				while (bx-- > 0) {
					numTiles--;
					tile = tiles[numTiles];
					tile.x = bx;
					tile.y = by;
					color = _bitmapData.getPixel(bx, by);
					tile.density = 1 - (color / 0xFFFFFF);
				}
			}
			
			// calc start
			bx = 0;
			by = _bitmapData.height;
			while (by --> 0) {
				if (_bitmapData.getPixel(bx, by) > PixTile.BLANK_THRESH * 0xFFFFFF) break;
			}
			_startP.x = bx;
			_startP.y = by;
			
			// calc end
			bx = _bitmapData.width;
			by = _bitmapData.height;
			while (by --> 0) {
				if (_bitmapData.getPixel(bx, by) > PixTile.BLANK_THRESH * 0xFFFFFF) break;
			}
			_endP.x = bx;
			_endP.y = by;
		}
		
		public function isCollision(x:Number, y:Number):Boolean {
			return bitmapData.getPixel(x / scaleX, y / scaleY) < PixTile.BLANK_THRESH * 0xFFFFFF;
		}
		 
		public function get bitmapData():BitmapData { return _bitmapData; }		
		public function set bitmapData(value:BitmapData):void {
			_bitmapData = value;
			update();
		}
		
		public function get scale():Number { return scaleX; }
		public function set scale(value:Number):void { scaleX = scaleY = value; }
		
		public function get startP():Point { return _startP; }
		
		public function get endP():Point { return _endP; }
	
	}

}